<template>
	<!-- 页面内容--补充联系人页面 -->
	<view style="width: 100vw; min-height: 100vh;background-color: #1F2022; color: #fff;">
		<formheadVue :headname="$t('contactArrangement.Supplementarycontacts')" :emptyleft='true'></formheadVue>
		<view class="P-head">
			<view class="P-2" style="margin-top: 20px;">
				<view v-for="(item, index) in contactsNum" :key="index" style="margin-bottom: 40rpx;">
					<view class="P-2-title flexrowstart">
						<image src="../../static/contacticon.png" mode=""></image>
						<text class="gradient-text">{{$t('contactArrangement.Supplementarycontacts')}}（{{item}}）</text>
					</view>
					<view style="margin-top: 20px;">
						<view style="margin-bottom: 10px;">
							<text
								style="font-size: 18px;font-weight: 500">{{$t('contactArrangement.relationship')}}</text>
						</view>
						<view :style="getBorderStyle(relationList[index])" class="P-5"
							@click="clickeFun('relationList' + numberToWord(item))">
							<uni-data-select :emptyTips="$t('emptyTips')" style="height: 100%;"
								:placeholder="$t('pleaseselect')" v-model="relationList[index]"
								:localdata="dropdowns.relationship" class="xiala"
								@change="handleSelectChange('relationList' + numberToWord(item))"></uni-data-select>
						</view>
					</view>
					<view style="margin-top: 20px;">
						<view style="margin-bottom: 10px;">
							<text style="font-size: 18px;font-weight: 500">{{$t('contactArrangement.name')}}</text>
						</view>
						<view class="P-5" :style="getBorderStyle(NameList[index])">
							<uni-easyinput style="height: 100%;" :placeholderStyle="from.placeholderStyle"
								:placeholder="$t('pleaseinput')" maxlength="30" v-model="NameList[index]"
								@blur="endTiming('NameList' + numberToWord(item))"
								@focus="startTiming('NameList' + numberToWord(item))"></uni-easyinput>
						</view>
					</view>
					<view style="margin-top: 20px;">
						<view style="margin-bottom: 10px;">
							<text
								style="font-size: 18px;font-weight: 500">{{$t('contactArrangement.Telephonenumber')}}</text>
						</view>
						<view class="P-5" :style="getBorderStyle(phoneNumList[index])">
							<input style="width: 100%; height: 100%;font-size: 16px;box-sizing: border-box;" type="text"
								v-model="phoneNumList[index]" :placeholder="$t('pleaseinput')" class="input"
								maxlength="10" inputmode="numeric"
								@blur="endTiming('phoneNumList' + numberToWord(item))"
								@focus="startTiming('phoneNumList' + numberToWord(item))" />
						</view>
					</view>
				</view>
			</view>
			<view class="P-6">
				<view class="content-1 flexcenter">
					<image src="../../static/worning.png" mode=""></image>
					<p>
						{{$t('contactArrangement.tips')}}
					</p>
				</view>
			</view>
			<view @click="fn1()" class="P-2 flexcenter">
				<p> {{$t('continue')}}</p>
			</view>
		</view>
	</view>
	</view>
</template>

<script>
	import formheadVue from '../../components/formhead.vue';
	import api from '@/pages/utils/api.js'
	// import setDot from '@/pages/utils/setdot.js';
	// import setfengkongDot from '@/pages/utils/fengkong.js';
	import getDroupMeunFun from '@/pages/utils/getDroupMeun.js'
	export default {
		data() {
			return {
				handleClick: false, //默认没点击,
				contactsNum: 0,
				dropdowns: {
					relationship: [], //职业
				},
				relationList: [],
				NameList: [],
				phoneNumList: [],
				from: {
					placeholderStyle: "color:#555555;font-size:16px;",
				},
				startTimes: {}, // 记录每个输入框的开始时间
				fillTimes: { // 存储填写时长
					relationListone: 0,
					relationListtwo: 0,
					relationListthree: 0,
					relationListfour: 0,

					NameListone: 0,
					NameListtwo: 0,
					NameListthree: 0,
					NameListfour: 0,

					phoneNumListone: 0,
					phoneNumListtwo: 0,
					phoneNumListthree: 0,
					phoneNumListfour: 0,

					page: 0
				},
				fieldMapping: [{
						name: 'yadz',
						phone: 'nbmw',
						relation: 'kfmy',
						relationName: 'nlpm'
					}, // 联系人1
					{
						name: 'adib',
						phone: 'iosm',
						relation: 'mcrm',
						relationName: 'xckb'
					}, // 联系人2
					{
						name: 'qumd',
						phone: 'uyaq',
						relation: 'jpcu',
						relationName: 'kqzb'
					}, // 联系人3
					{
						name: 'feux',
						phone: 'kqti',
						relation: 'vwgp',
						relationName: 'mzpa'
					} // 联系人4
				]
			}
		},
		components: {
			formheadVue
		},
		// onBackPress(options) {
		// 	if (options.from === 'navigateBack') {
		// 		return false;
		// 	}
		// 	return true;
		// },
		computed: {
			getBorderStyle() {
				return (value) => {
					return this.checkempty(value) ? {
						border: '6rpx solid #FDF57C',
						borderRadius: '34rpx',
						width: '100%'
					} : {};
				};
			},
		},
		watch: {
			phoneNumList: {
				handler(newVal) {
					newVal.forEach((num, index) => {
						let value = num.toString().replace(/[^0-9]/g, ''); // 仅保留数字

						// 自动补 0（如果首位不是 0，并且当前有值）
						if (value.length > 0 && value.charAt(0) !== '0') {
							value = '0' + value;
						}


						// 限制最大长度为 10 位
						if (value.length > 10) {
							value = value.slice(0, 10);
						}

						// **只有当值发生变化时才更新数组，避免死循环**
						if (value !== this.phoneNumList[index]) {
							this.$nextTick(() => {
								this.$set(this.phoneNumList, index, value);
							})
						}
						console.log('phoneNumList', this.phoneNumList);
					});
				},
				deep: true, // 监听数组内部的变化
			},
			NameList: {
				handler(newVal) {
					newVal.forEach((name, index) => {
						let value = name.toString();

						// **1. 只允许输入英文、空格、泰文字符、点（.）**
						value = value.replace(/[^a-zA-Z0-9\u0E00-\u0E7F .]/g, '');

						// **2. 去掉前后空格**
						value = value.trim();

						// **3. 如果全是空格、全是点或空格+点的组合，则清空**
						if (/^[\s.]+$/.test(value) || value === "") {
							value = "";
						}

						// **4. 只有当值发生变化时才更新，避免死循环**
						if (value !== this.NameList[index]) {
							this.$nextTick(() => {
								this.$set(this.NameList, index, value);
							})
						}
					});
				},
				deep: true, // 深度监听
			},
		},
		created() {
			console.log('created');
			api.getContactsSetting({
				key: 'alternateContact',
			}).then(data => {
				console.log('data---》》', data);
				this.$nextTick(() => {
					this.contactsNum = Number(data.alternateContact)
				})
				console.log('this.contactsNum', this.contactsNum);
			})
		},
		onShow() {
			this.startTiming('page')
			//重新计算下拉框的填写时长
			this.clearSelectStartFlags()
			this.loadDropdownData();
		},
		methods: {
			numberToWord(num) {
				const map = {
					1: 'one',
					2: 'two',
					3: 'three',
					4: 'four'
				};
				return map[num] || '';
			},
			clickeFun(field) {
				// const key = `${field}Changebegin`;
				// console.log('存储的key值', key);
				// if (!uni.getStorageSync(key)) {
				// 	this.startTiming(field);
				// 	uni.setStorageSync(key, true)
				// }
			},
			handleSelectChange(field) {
				// console.log('结束了，村上了吗', field);
				// const key = `${field}Changebegin`;
				// if (uni.getStorageSync(key)) {
				// 	this.endTiming(field);
				// }
			},
			clearSelectStartFlags() {
				// const keys = [
				// 	'relationListoneChangebegin',
				// 	'relationListtwoChangebegin',
				// 	'relationListthreeChangebegin',
				// 	'relationListfourChangebegin',
				// ];
				// keys.forEach(key => uni.removeStorageSync(key));
			},
			// 开始计时
			startTiming(field) {
				this.startTimes[field] = Date.now();
			},
			// 结束计时并计算时长
			endTiming(field) {
				console.log('计算结束时长', field);
				if (this.startTimes[field]) {
					const endTime = Date.now();
					this.fillTimes[field] = endTime - this.startTimes[field];
					this.startTimes[field] = null; // 重置
				}
			},
			async loadDropdownData() {
				try {
					const types = ["relationship"];
					const promises = types.map(type => getDroupMeunFun(type));

					const results = await Promise.all(promises);
					types.forEach((type, index) => {
						this.dropdowns[type] = results[index]?.map(item => ({
							value: item.ggbb,
							text: item.cjfu
						})) || [];
					});
				} catch (error) {
					console.error("获取下拉数据失败", error);
				}
			},
			checkempty(name) {
				if ((name == undefined || name == '') && this.handleClick) {
					return true
				} else {
					return false
				}
			},
			fn1() {
				this.handleClick = true;
				console.log('姓名数组', this.NameList);
				console.log('号码数组', this.phoneNumList);
				console.log('关系数组', this.relationList);

				// 1. 校验输入完整性
				for (let i = 0; i < this.contactsNum; i++) {
					if (!this.NameList[i] || !this.relationList[i] || !this.phoneNumList[i]) {
						console.log('请填写完整的联系人信息！');
						uni.showToast({
							icon: 'none',
							title: this.$t('contactArrangement.pagetips')

						})
						return;
					}
					if (!this.isValidPhoneNumber(this.phoneNumList[i])) {
						console.log(`第 ${i + 1} 个电话号码格式不正确，必须是 10 位数字！`);
						uni.showToast({
							icon: 'none',
							title: this.$t('contactArrangement.phonetips')
						})
						return;
					}
				}

				// 2. 校验重复
				if (this.hasDuplicates(this.phoneNumList)) {
					uni.showToast({
						icon: 'none',
						title: this.$t('contactArrangement.errorphone')
					});
					return;
				}
				if (this.hasDuplicates(this.relationList)) {
					uni.showToast({
						icon: 'none',
						title: this.$t('contactArrangement.errorrelationship')
					});
					return;
				}

				// 3. 构建上传参数
				let params = {
					qmsq: 1,
					vjeu: '3'
				};
				for (let i = 0; i < this.contactsNum; i++) {
					const mapping = this.fieldMapping[i];
					if (!mapping) break;

					params[mapping.name] = this.NameList[i];
					params[mapping.phone] = this.phoneNumList[i];
					params[mapping.relation] = this.relationList[i];

					const relationObj = this.dropdowns.relationship.find(item => item.value === this.relationList[i]);
					params[mapping.relationName] = relationObj ? '5' : '5';
				}



				api.uploadUserInfo(params).then(data => {
					console.log('存储联系人信息成功');
					this.endTiming('page');
					console.log('页面各种时长', this.fillTimes);

					const lowerKeys = ['one', 'two', 'three', 'four'];
					const upperKeys = ['One', 'Two', 'Three', 'Four'];
					const dotTypes = [{
							prefix: 'Relationship',
							field: 'relationList'
						},
						{
							prefix: 'Name',
							field: 'NameList'
						},
						{
							prefix: 'PhoneNumber',
							field: 'phoneNumList'
						}
					];
					// 页面跳转
					console.log('跳转到单据提交');
					uni.reLaunch({
						url: '/pages/demo7/demo7'
					})
				});
			},
			hasDuplicates(array) {
				return new Set(array).size !== array.length;
			},
			isValidPhoneNumber(phone) {
				return /^\d{10}$/.test(phone);
			},
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .uni-input-input {
		font-size: 16px !important;
	}

	::v-deep .uni-input-placeholder {
		color: #999 !important;
		font-size: 16px !important;
	}

	.P-5 {
		width: 100%;
		background-image: url('/static/inputborder.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;
		padding: 6rpx 20rpx;
		box-sizing: border-box;
		height: 100rpx;
	}

	.flexrowspacebetween {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.flexrowstart {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.flexcenter {
		display: flex;
		justify-content: center;
		align-items: center;
		align-content: center;
	}


	::v-deep .uni-input-input {
		font-size: 16px !important;
	}

	::v-deep .uni-input-placeholder {
		color: #999 !important;
		font-size: 16px !important;
	}

	.P-head {
		width: 100%;
		background-color: #1F2022;
		border-radius: 30rpx 30rpx 0rpx 0rpx;
		padding: 30rpx;
		box-sizing: border-box;
		margin-top: -110rpx;


		image {
			width: 100rpx;
			height: 100rpx;
		}
	}

	.P-1 {
		margin-top: 20px;

		image {
			width: 100%;
			height: 100rpx;
		}
	}

	.P-2 {
		width: 100%;
		margin: 20rpx 0rpx;

		.P-2-title {
			height: 100rpx;
			background-image: url('../../static/tipsbg.png');
			background-repeat: no-repeat;
			background-size: 100% 100%;
			padding: 0rpx 20rpx;

			image {
				width: 50rpx;
				height: 50rpx;
				margin-right: 40rpx;
			}
		}

		.gradient-text {
			background: linear-gradient(to bottom, rgba(204, 154, 243, 1), #F9E4B7);
			-webkit-background-clip: text;
			-webkit-text-fill-color: transparent;
			font-weight: bold;
			font-size: 32rpx;
			/* 根据需要调节 */
		}

		p {
			width: 86%;
			height: 90rpx;
			background-color: #FFF584;
			text-align: center;
			color: #000;
			line-height: 90rpx;
			border-radius: 20rpx;
			font-size: 40rpx;
			box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.2);
			transition: all 0.2s;
			// animation: pulsebtn 1.2s ease-in-out infinite;

		}

		p:active {
			transform: scale(0.96);
			box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
		}

		@keyframes pulsebtn {
			0% {
				transform: scale(1);
			}

			50% {
				transform: scale(1.08);
			}

			100% {
				transform: scale(1);
			}
		}

	}

	.P-6 {
		background-color: #393A3D;
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		font-size: 28rpx;
		margin-bottom: 40rpx;

		.content-1 {
			box-sizing: border-box;
			color: #FF9E6F;

			image {
				width: 43rpx;
				height: 43rpx;
			}

			p {
				margin-left: 20rpx;
				width: 88%;
			}

		}
	}

	.flexcentercloumn {
		display: flex;
		justify-content: center;
		align-items: center;
		align-content: center;
		flex-direction: column;
	}
</style>